#!/user/bin/even Python3
# -*- coding:utf-8 -*-
# GuiData.py
# Gui页面相关数据整理-Ymal文件方式
# author:zhaohexin
# time：2020/5/21 16:22
import configparser
import os
import platform

import yaml
from configobj import ConfigObj

base_path = os.path.abspath(".")


def system_data(path=None):
    """
    获取系统默认数据
    :param path:
    :return:
    """
    if not path:
        if os.path.exists(os.path.join(base_path, 'ASetOfTablesSetting.ini')):
            # 存在，获取相关数据
            # 读取配置文件并赋值返回
            cf = configparser.ConfigParser()
            cf.read(os.path.join(base_path, "ASetOfTablesSetting.ini").replace("\\", "/"), encoding='UTF-8')
            try:
                eval(cf.get("TESTCASE", "CASES_PATH"))
                path = os.path.join(base_path, "YmlFile").replace("\\", "/")
            except Exception as e:
                path = cf.get("TESTCASE", "CASES_PATH").replace("\\", "/")
        else:
            path = os.path.join(base_path, "YmlFile").replace("\\", "/")

    all_module = {}
    businessid_module = {}
    statisticsend_module = {}
    cases = {}
    all_case = {}

    # 便利文件夹中路径，生成相应信息
    for root, dirs, files in os.walk(os.path.join(path, "BusinessSide")):
        for file in files:
            with open(os.path.join(path, "BusinessSide", file), 'r', encoding="utf-8") as f:
                yml_data = f.read()
                # load方法转出为字典类型
                data = yaml.load(yml_data)
                businessid_module[f"BusinessSide.{file.split('.')[0]}"] = f"{data['TestName']}_{data['Story']}"
                all_module[f"BusinessSide.{file.split('.')[0]}"] = f"{data['TestName']}_{data['Story']}"
                for case in data["Case"]:
                    cases[f"BusinessSide.{file.split('.')[0]}|{case['CaseNumber']}"] = case["CaseName"]
                f.close()

    for root, dirs, files in os.walk(os.path.join(path, "TheStatisticsEnd")):
        for file in files:
            with open(os.path.join(path, "TheStatisticsEnd", file), 'r', encoding="utf-8") as f:
                yml_data = f.read()
                # load方法转出为字典类型
                data = yaml.load(yml_data)
                statisticsend_module[f"TheStatisticsEnd.{file.split('.')[0]}"] = f"{data['TestName']}_{data['Story']}"
                all_module[f"TheStatisticsEnd.{file.split('.')[0]}"] = f"{data['TestName']}_{data['Story']}"
                for case in data["Case"]:
                    cases[f"TheStatisticsEnd.{file.split('.')[0]}|{case['CaseNumber']}"] = case["CaseName"]
                f.close()

    for key, value in cases.items():
        if all_module.get(key.split("|")[0]):
            if all_case.get(all_module.get(key.split("|")[0])) is None:
                all_case[all_module.get(key.split("|")[0])] = [value]
            else:
                all_case[all_module.get(key.split("|")[0])].append(value)
    return {"all_module": all_module,
            "businessid_module": businessid_module,
            "statisticsend_module": statisticsend_module,
            "cases": cases,
            "all_case": all_case,
            }


def data_acquisition(path=None):
    """
    数据获取
    :return:
    """
    system_datas = system_data(path)
    # 判断是否存在配置文件
    if os.path.exists(os.path.join(base_path, 'ASetOfTablesSetting.ini')):
        # 存在，获取相关数据
        # 读取配置文件并赋值返回
        cf = configparser.ConfigParser()
        cf.read(os.path.join(base_path, "ASetOfTablesSetting.ini"), encoding='UTF-8')
        # 获取浏览器
        run_browser = cf.get("DEFULT", "RUN_BROWSER")
        run_browser_path = cf.get("DEFULT", "RUN_BROWSER_PATH")
        # 获取浏览器路径插件
        customize_plugin_path = cf.get("DEFULT", "CUSTOMIZE_PLUGIN_PATH")
        if '""' == customize_plugin_path:
            customize_plugin_path = "默认当前目录下存储"
        # 获取统计端路径
        businesside_url = cf.get("DEFULT", "BUSINESSSIDE_URL")
        # 获取企业端路径
        thestatisticsend_url = cf.get("DEFULT", "THESTATISTICSEND_URL")
        # 获取浏览器尺寸
        base_size = cf.get("DEFULT", "BASE_SIZE")
        browser_size = []
        try:
            if base_size and base_size.split(",")[0] != '""':
                if base_size == '800, 600':
                    base_size = [False, True, False]
                else:
                    browser_size = [str(int(base_size.split(",")[0])), str(int(base_size.split(",")[1]))]
                    base_size = [False, False, True]
            else:
                base_size = [True, False, False]
        except Exception as e:
            base_size = [True, False, False]

        # 获取错误截图配置
        report_image_path = cf.get("REPORT", "REPORT_IMAGE_PATH")
        if '""' == report_image_path:
            report_image_path = "默认当前目录下存储"
        # 获取报告存储路径配置
        report_file_path = cf.get("REPORT", "REPORT_FILE_PATH")
        if '""' == report_file_path:
            report_file_path = "默认当前目录下存储"
        # 获取用例文件目录
        case_file_path = cf.get("TESTCASE", "CASES_PATH")
        if '""' == case_file_path:
            case_file_path = "默认当前目录下存储"
        # 获取选择执行用例配置

        excution = [i.strip() for i in
                    (list(filter(None, cf.get("TESTCASE", "EXECUTION_SYSTEM").split(","))) if cf.get("TESTCASE",
                                                                                                     "EXECUTION_SYSTEM") != '""' else []
                     )]
        if excution and len(excution) != 2:
            if excution[0] == "TheStatisticsEnd":
                excution_system = "企业端"
            elif excution[0] == "BusinessSide":
                excution_system = "统计端"
            else:
                excution_system = "全部"
        else:
            excution_system = "全部"
        # 获取已选中的模块
        excution_module = []
        for module in cf.get("TESTCASE", "EXECUTION_MODULE").split(","):
            if system_datas["all_module"].get(module.strip()) and system_datas["all_module"].get(module.strip()):
                excution_module.append(system_datas["all_module"].get(module.strip()))

        # 获取以选中功能
        excution_cases = []
        for case in cf.get("TESTCASE", "EXECUTION_CASES").split(","):
            if system_datas["cases"].get(case.strip()):
                excution_cases.append(system_datas["cases"].get(case.strip()))
        # 获取Linux管理员用户密码
        root_password = cf.get("DEFULT", "ROOTPASSWORD")

        # 返回数据值
        return {"run_browser": run_browser,
                "run_browser_path": run_browser_path,
                "customize_plugin_path": customize_plugin_path,
                "businesside_url": businesside_url,
                "thestatisticsend_url": thestatisticsend_url,
                "base_size": base_size,
                "browser_size": browser_size,
                "report_image_path": report_image_path,
                "report_file_path": report_file_path,
                "case_file_path": case_file_path,
                "excution_system": excution_system,
                "excution_module": excution_module,
                "excution_cases": excution_cases,
                "all_cases": system_datas["all_case"],
                "all_module": [key for key in system_datas["all_module"].values()],
                "businessid_module": [key for key in system_datas["businessid_module"].values()],
                "statisticsend_module": [key for key in system_datas["statisticsend_module"].values()],
                "root_password": root_password
                }
    else:
        # 不存在，返回默认值
        module_values = [key for key in system_datas["all_module"].values()]
        return {"run_browser": "Chrome",
                "run_browser_path": "",
                "customize_plugin_path": "默认当前目录下存储",
                "businesside_url": "http://192.168.1.235:7001/yyaq",
                "thestatisticsend_url": "http://192.168.1.235:7001/bjstat_web",
                "base_size": [True, False, False],
                "browser_size": [],
                "report_image_path": "默认当前目录下存储",
                "report_file_path": "默认当前目录下存储",
                "case_file_path": "默认当前目录下存储",
                "excution_system": "全部",
                "excution_module": [],
                "excution_cases": [],
                "all_cases": system_datas["all_case"],
                "all_module": [key for key in system_datas["all_module"].values()],
                "businessid_module": [key for key in system_datas["businessid_module"].values()],
                "statisticsend_module": [key for key in system_datas["statisticsend_module"].values()],
                "root_password": ""
                }


def data_store(values):
    """
    进行数据存储
    :param values: UI界面传回的值
    :return:
    """
    # 先删除原有配置文件
    try:
        os.remove(os.path.join(base_path, 'ASetOfTablesSetting.ini'))
    except Exception as e:
        pass
    # 获取具体执行用例文件信息
    if values["case_file_path"]:
        system_datas = system_data(values["case_file_path"].replace('\\', '/'))
    else:
        system_datas = system_data(os.path.join(os.path.abspath("."), "YmlFile").replace('\\', '/'))
    # 写入配置文件
    config = ConfigObj(os.path.join(base_path, "ASetOfTablesSetting.ini"), encoding='UTF8')
    config['DEFULT'] = {}
    config['DEFULT']['RUN_BROWSER'] = values["run_browser"]
    if values["run_browser"] == "360安全浏览器" and values["run_browser_path"] == "" and platform.system() == "Linux":
        config['DEFULT']['RUN_BROWSER_PATH'] = "/usr/bin/browser360-cn"
    else:
        config['DEFULT']['RUN_BROWSER_PATH'] = values["run_browser_path"]
    config['DEFULT']['CUSTOMIZE_PLUGIN_PATH'] = values["customize_plugin_path"].replace('\\', '/')
    config['DEFULT']['BUSINESSSIDE_URL'] = values["businesside_url"]
    config['DEFULT']['THESTATISTICSEND_URL'] = values["thestatisticsend_url"]
    config['DEFULT']['BASE_SIZE'] = values["browser_size"]
    config['REPORT'] = {}
    config['REPORT']['REPORT_IMAGE_PATH'] = values["report_image_path"].replace('\\', '/')
    config['REPORT']['REPORT_FILE_PATH'] = values["report_file_path"].replace('\\', '/')
    config['TESTCASE'] = {}
    if values["excution_system"] == "统计端":
        config['TESTCASE']['EXECUTION_SYSTEM'] = ['BusinessSide']
    elif values["excution_system"] == "企业端":
        config['TESTCASE']['EXECUTION_SYSTEM'] = ['TheStatisticsEnd']
    else:
        config['TESTCASE']['EXECUTION_SYSTEM'] = []
    excution_modules = []
    excution_cases = []
    for value in values["excution_module"]:
        excution_module = [k for k, v in system_datas["all_module"].items() if v == value]
        excution_modules.append(excution_module[0])
        for case_value in values["excution_cases"][value]:
            excution_case = [k for k, v in system_datas["cases"].items() if v == case_value and excution_module[0] in k]
            excution_cases.append(excution_case[0])
    config['TESTCASE']['EXECUTION_MODULE'] = excution_modules

    config['TESTCASE']['EXECUTION_CASES'] = excution_cases
    config['TESTCASE']['CASES_PATH'] = values["case_file_path"].replace('\\', '/')
    config['DEFULT']['ROOTPASSWORD'] = values["root_password"]
    config.write()


if __name__ == '__main__':
    print(os.path.isdir("/home/zhx/桌面"))